package com.gitee.kamismile.gatewayAgent.client.handler;

import com.gitee.kamismile.stone.commmon.util.JsonUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lidong on 2017/2/8.
 */
public class GateWayClientHandler extends SimpleChannelInboundHandler<Message.RouterMessage> {

    private final Logger logger = LoggerFactory.getLogger("bLog");

    // Stateful properties
    private volatile Channel channel;

    public GateWayClientHandler() {
        super(false);
    }

//    public void sendMessage(String cmdInfo, String data, Long seq, String router) {
//        Message.RouterMessage.Builder msg = Message.RouterMessage.newBuilder();
//        Message.RouterRequest.Builder request = Message.RouterRequest.newBuilder();
//        request.setSeq(seq);
//        request.setRouter(router);
//        Message.Command.Builder cmd = Message.Command.newBuilder();
//        cmd.setCommand(cmdInfo);
//        request.setCmd(cmd);
//        request.setSerializedData(ByteString.copyFrom(data.getBytes()));
//        msg.addRequest(request);
//        channel.writeAndFlush(msg);
//
//    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        channel = ctx.channel();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message.RouterMessage msg) throws Exception {
        ctx.executor().execute(() -> {
            logger.info(msg.toString());
        });
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
